package cn.com.wangluotongxin.netty.event;

import cn.com.wangluotongxin.chat.netty.ChatNettyQueue;
import cn.com.wangluotongxin.chat.netty.pojo.LoginRequestInfo;
import cn.com.wangluotongxin.netty.constants.MsgType;
import cn.com.wangluotongxin.netty.constants.Result;
import cn.com.wangluotongxin.netty.pojo.NettyResponse;
import cn.com.wangluotongxin.rabitmq.service.RabbitMqService;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSONObject;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

@Component
public class LoginEventHandler implements ApplicationListener<LoginEvent> {

    @Autowired
    private RabbitMqService rabbitMqService;

    @Override
    public void onApplicationEvent(LoginEvent event) {
        if(MapUtil.isEmpty(event.getMessageMap())) return;

        String clientId = MapUtil.getStr(event.getMessageMap(), "clientId", "");
        LoginRequestInfo info = new LoginRequestInfo()
                .setChannelId(event.getChannel().id().asLongText())
                .setClientId(clientId)
                .setDate(DateUtil.date());
        rabbitMqService.sendMessage(ChatNettyQueue.CHAT_LOGIN, info);

        NettyResponse response = new NettyResponse()
                .setMsgType(MsgType.LOGIN_RESPONSE)
                .setResult(Result.SUCCESS.getCode())
                .setDateTime(DateUtil.date().getTime());
        event.getChannel().writeAndFlush(new TextWebSocketFrame(JSONObject.toJSONString(response)));
    }
}
